<!--
 * @Description: 点菜页面口味面板组件（右侧面板）
-->
<template>
  <div class="practice-panel" v-if="currentFoodData">
    <div class="title">{{ currentFoodData.name }}口味</div>

    <div class="selected-box">
      <div class="label">已选：</div>
      <div class="chips">
        <div class="chip" v-for="(name, idx) in selectedNames" :key="name + idx">
          <div class="ellipsis">{{ name }}</div>
          <el-icon class="close-icon" @click.stop="deleteChip(name)"><Close /></el-icon>
        </div>
      </div>
    </div>

    <div class="category-box-content">
      <div class="tabs-box">
        <div
          class="tab-item"
          :class="{ active: activeCategoryIndex === index }"
          v-for="(cat, index) in categoryList"
          :key="cat.id || cat.name || index"
          @click="handleSelectCategory(index, cat)"
        >
          {{ cat.name }}
        </div>
      </div>
      <div v-loading="listLoading" class="list-box-content">
        <div class="list-box" v-if="!showNoData">
          <div
            class="list-item"
            :class="{ active: isSelected(item) }"
            v-for="item in tasteList"
            :key="item.id"
            @click="toggleSelect(item)"
          >
            <div class="name">{{ item.name }}</div>
          </div>
          <div
            class="list-item-zhanwei"
            v-for="val in ['a', 'b', 'c', 'd']"
            :key="'zw' + val"
          ></div>
        </div>
        <div class="no-data-box" v-else>
          <NotData desc="暂无口味数据" />
        </div>
      </div>

      <div class="count-choose-box">
        <div class="selected"></div>
        <div class="total" v-if="selectedNames.length">共{{ selectedNames.length }}项</div>
      </div>
    </div>

    <div class="btn-box">
      <div class="desc">
        <span v-if="selectedNames.length">已选：（{{ practiceNameList }} ）</span>
      </div>
      <div class="two-btn">
        <el-button class="delete-btn" @click="handleBack">返回</el-button>
        <el-button class="delete-btn" @click="handleClearAll">全部清除</el-button>
        <el-button class="write-btn" @click="showWrite = true">手写口味</el-button>
        <el-button class="confirm-btn" :loading="loading" @click="handleConfirm"
          >确认修改</el-button
        >
      </div>
    </div>

    <CustomDialog v-model:visible="showWrite" :isClose="true" top="20vh">
      <div class="write-box">
        <div class="write-title">手写口味</div>
        <div class="row">
          <div class="label">口味名称</div>
          <div class="input-container">
            <input class="input" v-model.trim="writeTasteName" placeholder="请输入口味名称" />
            <img
              class="clear-icon"
              src="@/assets/images/home/input-clear.png"
              alt="清除"
              @click="writeTasteName = ''"
              v-show="writeTasteName"
            />
          </div>
        </div>
        <div class="btn-box">
          <el-button class="cancel-btn" @click="showWrite = false">取消</el-button>
          <el-button class="confirm-btn" @click="handleAddWriteTaste"> 添加 </el-button>
        </div>
      </div>
    </CustomDialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { ElIcon } from 'element-plus'
import { Close } from '@element-plus/icons-vue'
import { tasteCategoryList, fetchTasteList } from '@/api/food'
import NotData from '@/components/NotData/Index.vue'
import CustomDialog from '@/components/CustomDialog/Index.vue'

interface Props {
  currentFoodData?: any
}

interface Emits {
  (e: 'back'): void
  (
    e: 'confirm',
    payload: { taste_ids: number[]; write_taste: string[]; selectedNames: string[] }
  ): void
}

const props = withDefaults(defineProps<Props>(), { currentFoodData: null })
const emit = defineEmits<Emits>()

const loading = ref(false)
const categoryList = ref<any[]>([])
const activeCategoryIndex = ref(-1)
const tasteList = ref<any[]>([])
const selectedTasteIds = ref<number[]>([])
const writeTasteList = ref<string[]>([])
const showNoData = ref(false)
const listLoading = ref(false)
const showWrite = ref(false)
const writeTasteName = ref('')

const selectedNames = computed(() => {
  const picked = tasteList.value.filter(t => selectedTasteIds.value.includes(t.id)).map(t => t.name)
  return [...picked, ...writeTasteList.value]
})
const practiceNameList = computed(() =>
  selectedNames.value.length ? selectedNames.value.join('、') : ''
)

const loadCategories = async () => {
  try {
    const res = await tasteCategoryList({})
    if (res.status === 200) {
      const list = Array.isArray(res.data) ? res.data : []
      // 在首位插入“全部”分类
      categoryList.value = [{ id: 0, name: '全部' }, ...list]
    }
  } catch (e) {}
}

const handleSelectCategory = async (index: number, cat: any) => {
  activeCategoryIndex.value = index
  try {
    listLoading.value = true
    // 选择“全部”时不带分类参数，加载全部口味
    const params = cat && Number(cat.id) !== 0 ? { category_id: cat.id } : {}
    const res = await fetchTasteList(params)
    if (res.status === 200) {
      tasteList.value = res.data || []
      showNoData.value = tasteList.value.length === 0
    }
  } finally {
    listLoading.value = false
  }
}

watch(
  () => props.currentFoodData,
  async newVal => {
    if (newVal) {
      selectedTasteIds.value = Array.isArray((newVal as any).taste_ids)
        ? (newVal as any).taste_ids
        : []
      writeTasteList.value = Array.isArray((newVal as any).write_taste)
        ? (newVal as any).write_taste
        : []
      activeCategoryIndex.value = -1
      tasteList.value = []
      showNoData.value = false
      await loadCategories()
      // 默认选中“全部”
      if (categoryList.value.length) handleSelectCategory(0, categoryList.value[0])
    }
  },
  { immediate: true }
)

const isSelected = (item: any) => selectedTasteIds.value.includes(item.id)
const toggleSelect = (item: any) => {
  const idx = selectedTasteIds.value.indexOf(item.id)
  if (idx > -1) selectedTasteIds.value.splice(idx, 1)
  else selectedTasteIds.value.push(item.id)
}

const handleAddWriteTaste = () => {
  if (!writeTasteName.value) {
    ElMessage.warning('请输入口味名称')
    return
  }
  if (writeTasteList.value.includes(writeTasteName.value)) {
    ElMessage.warning('该手写口味名称已存在，名称不能重复添加！')
    return
  }
  writeTasteList.value.push(writeTasteName.value)
  writeTasteName.value = ''
  showWrite.value = false
}

const deleteChip = (name: string) => {
  const item = tasteList.value.find(t => t.name === name)
  if (item) {
    const idx = selectedTasteIds.value.indexOf(item.id)
    if (idx > -1) selectedTasteIds.value.splice(idx, 1)
  }
  writeTasteList.value = writeTasteList.value.filter(n => n !== name)
}

const handleClearAll = () => {
  selectedTasteIds.value = []
  writeTasteList.value = []
}

const handleConfirm = () => {
  emit('confirm', {
    taste_ids: selectedTasteIds.value,
    write_taste: writeTasteList.value,
    selectedNames: selectedNames.value
  })
}

const handleBack = () => emit('back')
</script>

<style scoped lang="scss">
.practice-panel {
  box-sizing: border-box;
  width: 976px;
  height: 986px;
  background: #ffffff;
  border-radius: 20px;
  box-shadow: 3px 0px 24px 0px rgba(0, 0, 0, 0.16);

  .title {
    height: 88px;
    background: #f4f4f4;
    border-radius: 20px 20px 0 0;
    line-height: 88px;
    font-size: 18px;
    font-family:
      PingFang SC,
      PingFang SC-Bold;
    font-weight: 700;
    text-align: center;
    color: #353535;
  }

  .selected-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px 32px;
    height: 92px;
    box-sizing: border-box;

    .label {
      font-size: 18px;
      font-family:
        PingFang SC,
        PingFang SC-Regular;
      font-weight: 400;
      color: #999999;
      margin-right: 10px;
    }
    .chips {
      display: flex;
      flex: 1;
      width: 0;
      overflow: auto;
      gap: 20px;
      .chip {
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 100px;
        flex-shrink: 0;
        padding: 0 10px;
        height: 52px;
        background: #7c0a03;
        border-radius: 12px;
        font-size: 18px;
        font-family:
          PingFang SC,
          PingFang SC-Regular;
        font-weight: 400;
        text-align: center;
        color: #fff;
        line-height: 52px;
      }
    }
  }

  .tabs-box {
    position: relative;
    box-sizing: border-box;
    width: 880px;
    height: 48px;
    background: #ffffff;
    border: 1px solid #d0d0d0;
    border-radius: 25px;
    display: flex;
    align-items: center;
    margin: 0 30px;

    .tab-item {
      display: inline-block;
      padding: 0 44px;
      height: 48px;
      line-height: 48px;
      font-size: 14px;
      font-family:
        PingFang SC,
        PingFang SC-Regular;
      font-weight: 400;
      text-align: center;
      color: #333333;
      cursor: pointer;
    }
    .active {
      color: #ffffff;
      background: #7c0a03;
      border-radius: 24px;
    }
  }

  .list-box {
    padding: 0px 20px 20px;
    box-sizing: border-box;
    overflow-y: auto;
    background: #f4f4f4;
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    flex-wrap: wrap;

    .list-item {
      min-width: 138px;
      padding: 0 10px;
      display: flex;
      align-items: center;
      flex-direction: column;
      justify-content: center;
      height: 70px;
      background: #ffffff;
      border-radius: 12px;
      font-family:
        PingFang SC,
        PingFang SC-Regular;
      font-weight: 400;
      text-align: center;
      margin-right: 10px;
      color: #333333;
      cursor: pointer;
      margin-top: 20px;

      .name {
        font-size: 18px;
        margin-bottom: 4px;
        text-align: center;
      }
    }
    .active {
      border: 1px solid #7c0a03;
      color: #7c0a03;
    }
  }

  .btn-box {
    padding: 0 30px;
    height: 112px;
    border-radius: 0 0 20px 20px;
    box-sizing: border-box;
    background: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .desc {
      font-size: 16px;
      font-family:
        PingFang SC,
        PingFang SC-Regular;
      font-weight: 400;
      color: #353535;
      line-height: 24px;
      max-width: 300px;
    }
    .two-btn {
      display: flex;
      align-items: center;

      .write-btn {
        width: 100px;
        height: 52px;
        background: #7c0a03;
        border-radius: 12px;
        line-height: 52px;
        font-size: 18px;
        font-family:
          PingFang SC,
          PingFang SC-Regular;
        font-weight: 400;
        text-align: center;
        color: #ffffff;
        cursor: pointer;
      }
    }
    .delete-btn {
      width: 100px;
      height: 52px;
      line-height: 52px;
      background: #ffffff;
      border: 1px solid #333333;
      border-radius: 12px;
      font-size: 18px;
      font-family:
        PingFang SC,
        PingFang SC-Regular;
      font-weight: 400;
      text-align: center;
      color: #333333;
      cursor: pointer;
      margin-right: 20px;
    }
    .confirm-btn {
      width: 200px;
      height: 52px;
      background: #7c0a03;
      border-radius: 12px;
      line-height: 52px;
      font-size: 18px;
      font-family:
        PingFang SC,
        PingFang SC-Regular;
      font-weight: 400;
      text-align: center;
      color: #ffffff;
      cursor: pointer;
      margin-left: 20px;
    }
  }

  .write-box {
    margin-top: 12px;
    padding: 10px;

    .write-title {
      font-size: 16px;
      color: #333;
      margin-bottom: 30px;
      text-align: center;
    }
    .row {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      margin: 20px 0;
      .label {
        width: 90px;
        color: #333;
        margin-right: 8px;
        font-size: 18px;
      }
      .input-container {
        display: flex;
        align-items: center;
        flex: 1;
        height: 40px;
        padding: 8px 12px 8px;
        background: #ffffff;
        border: 1px solid #d2d2d2;
        border-radius: 12px;
        box-sizing: border-box;
        .input {
          outline: none;
          border: none;
          width: 100%;
          font-size: 14px;
          color: #333333;
        }
        .clear-icon {
          flex-shrink: 0;
          width: 18px;
          height: 18px;
          cursor: pointer;
        }
      }
    }

    .btn-box {
      padding: 20px 0 0;
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: auto !important;
      .cancel-btn {
        width: 190px;
        height: 52px;
        border: 1px solid #d2d2d2;
        border-radius: 12px;
        font-size: 18px;
        font-family:
          PingFang SC,
          PingFang SC-Regular;
        font-weight: 400;
        text-align: center;
        color: #353535;
        line-height: 52px;
        cursor: pointer;
      }

      .confirm-btn {
        width: 190px;
        height: 52px;
        background: #7c0a03;
        border-radius: 12px;
        font-size: 18px;
        font-family:
          PingFang SC,
          PingFang SC-Regular;
        font-weight: 400;
        text-align: center;
        color: #ffffff;
        line-height: 52px;
        cursor: pointer;

        &.loading {
          opacity: 0.7;
          cursor: not-allowed;
        }
      }
    }
  }
}
.category-box-content {
  padding: 20px;
  background-color: #f4f4f4;
  height: 640px;
}
.count-choose-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
}
.close-icon {
  cursor: pointer;
}
.list-box-content {
  height: 580px;
}
</style>
